﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Outlook; 

namespace pstMover
{
    class pstMover
    {
        static void Main(string[] args)
        {
            try 
            {
                Application app = new ApplicationClass();
                NameSpace NS = app.GetNamespace("MAPI");
                MAPIFolder inboxFld = NS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
                MAPIFolder newFolder = inboxFld.Folders.Add("PST-Repository", Type.Missing);
                IEnumerable<MailItem> mailItems = readPst(@"\\mgofrd1\redirect03\g521601\My Documents\Outlook Files\myPST.pst", "myPST"); 
                foreach (MailItem mailItem in mailItems) 
                {
                    mailItem.Move(newFolder);
                } 
            }
            catch (System.Exception ex) 
            { 
                Console.WriteLine(ex.Message); 
            } 
        }

        private static IEnumerable<MailItem> readPst(string pstFilePath, string pstName)
        {
            List<MailItem> mailItems = new List<MailItem>();
            Application app = new Application();
            NameSpace outlookNs = app.GetNamespace("MAPI");
            // Add PST file (Outlook Data File) to Default Profile             
            outlookNs.AddStore(pstFilePath);             
            MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder();             // Traverse through all folders in the PST file             
            // TODO: This is not recursive, refactor             
            Folders subFolders = rootFolder.Folders;             
            foreach (Folder folder in subFolders) 
            {                 
                Items items = folder.Items;
                foreach (object item in items) 
                {
                    if (item is MailItem) 
                    {
                        MailItem mailItem = item as MailItem;
                        mailItems.Add(mailItem);  
                    }
                }
            }
            // Remove PST file from Default Profile       
            outlookNs.RemoveStore(rootFolder);      
            return mailItems;         
        } 
    }
}